package com.p2p.auth.controller.api.crm;


import com.p2p.auth.common.base.JsonResult;
import com.p2p.auth.common.base.ProcessAPI;
import com.p2p.auth.common.base.ResponseBase;
import com.p2p.auth.common.base.ResultCode;
import com.p2p.auth.controller.Routes;
import com.p2p.auth.domain.dto.user.LoginRequestDTO;
import com.p2p.auth.domain.dto.visitor.VisitorQueryDTO;
import com.p2p.auth.domain.dto.visitor.VisitorRequestDTO;
import com.p2p.auth.domain.dto.visitor.VisitorResponseDTO;
import com.p2p.auth.domain.entity.UserRole;
import com.p2p.auth.domain.entity.Visitor;
import com.p2p.auth.service.lifeCycle.VisitorUtils;
import com.p2p.auth.service.repository.UserRoleRepository;
import com.p2p.auth.service.repository.VisitorRepository;
import com.p2p.auth.service.specification.VisitorSpecification;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.annotations.common.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lipei on 2017/4/18.
 */

@RestController
@Api(value = "访客API", description = "访客相关的CRUD操作，只有认证成功的访客才允许登陆后台系统，注意必传参数与参数")
public class CrmVisitorController {
    public static final String Visitor_NAME = null;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private VisitorRepository visitorRepository;

    @Autowired
    private UserRoleRepository userRoleRepo;


    @ApiOperation(value="用户登录" , notes = "输入手机号和密码进行登录" , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "req" , value="用户姓名和密码", required = true , dataType = "LoginRequestDTO")
    @RequestMapping(value = Routes.CRM_VISITOR_LOGIN, method = RequestMethod.POST)
    public ResponseBase<VisitorResponseDTO> checkBalance(@RequestBody LoginRequestDTO req) {
        ResponseBase<VisitorResponseDTO> resp = new ResponseBase<>();

        if (req == null || StringHelper.isEmpty(req.getPhoneNum()) || StringHelper.isEmpty(req.getPwd())) {
            resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
            String errorMsg = ResultCode.PARAM_ERROR.getMsg();
            resp.setMsg(errorMsg);
            logger.error("请求信息参数错误。");
            return resp;
        }

        String phoneNum = req.getPhoneNum();

        String pwd = req.getPwd();

        Visitor visitor = visitorRepository.findByVisitorPhoneNum(phoneNum);

        if(visitor == null){
            resp.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
            resp.setMsg(ResultCode.USER_NOT_EXIST.getMsg());
        }else if(StringHelper.isEmpty(visitor.getPassword()) || visitor.getPassword().equals(pwd) == false){
            resp.setResultCode(ResultCode.USER_PASS_ERROR.getCode());
            resp.setMsg(ResultCode.USER_PASS_ERROR.getMsg());
        }else {
            VisitorResponseDTO visitorResp = VisitorUtils.copyToDTO(visitor);
            resp.setResult(visitorResp);
            resp.setResultCode(ResultCode.SUCC.getCode());
        }
        return resp;
    }



    @ApiOperation(value = "添加后台操作者", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.CRM_VISITOR_ADD, method = RequestMethod.POST)
    public JsonResult getAllVisitor(HttpServletRequest request, @RequestBody  VisitorRequestDTO req) {
        ProcessAPI api = (result, validate) -> {
            if (req == null || StringUtils.isEmpty(req.getVisitorPhoneNum())) {
                result.setMsg("手机号码为空，此次添加失败!");
                result.setResultCode(ResultCode.PARAM_ERROR.getCode());
                return ;
            }

            if (req == null || StringUtils.isEmpty(req.getVisitorRealName())) {
                result.setMsg("姓名为空，此次添加失败!");
                result.setResultCode(ResultCode.PARAM_ERROR.getCode());
                return ;
            }

            Visitor dbVisitor = visitorRepository.findByVisitorPhoneNum(req.getVisitorPhoneNum());

            if(dbVisitor != null){
                result.setMsg("该管理员用户已存在，此次添加失败!");
                result.setResultCode(ResultCode.USER_EXIST.getCode());
                return ;
            }

            Visitor visitorPo = VisitorUtils.copyToPO(req);
            visitorRepository.save(visitorPo);
            VisitorResponseDTO visitorResponseDTO = VisitorUtils.copyToDTO(visitorPo);
            result.setResult(visitorResponseDTO);
            result.setSize(Long.valueOf(1));

        };
        return api.process(request);
    }

    @ApiOperation(value = "查询所有后台操作者", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.CRM_VISITOR_ALL, method = RequestMethod.GET)
    public JsonResult getAllVisitor(HttpServletRequest request, VisitorQueryDTO req) {
        ProcessAPI api = (result, validate) -> {
            Specification<Visitor> specification = VisitorSpecification.buildFromDTO(req);
            Page<Visitor> VisitorPage = visitorRepository.findAll(specification, req.getPage());
            List<VisitorResponseDTO> VisitorRespList = new ArrayList<>();
            VisitorPage.forEach(l -> {
                VisitorResponseDTO dto = VisitorUtils.copyToDTO(l);
                if(StringHelper.isNotEmpty(l.getRoleId())){
                    UserRole userRole = userRoleRepo.findByRoleId(l.getRoleId());
                    if(userRole != null && StringHelper.isNotEmpty(userRole.getName())){
                        dto.setRoleStr(userRole.getName());
                    }
                }

                VisitorRespList.add(dto);
            });
            result.setResult(VisitorRespList);
            result.setSize(VisitorPage.getTotalElements());
        };
        return api.process(request);
    }

    @ApiOperation(value = "修改操作用户基本信息", notes = "修改操作用户基本信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value =Routes.CRM_VISITOR_UPD, method = RequestMethod.PUT)
    public ResponseBase<VisitorResponseDTO> updateVisitorNameVisitorDescription(@RequestBody VisitorRequestDTO visitorRequestDTO) {
        ResponseBase<VisitorResponseDTO> result = new ResponseBase<>();

        if (visitorRequestDTO == null || StringUtils.isEmpty(visitorRequestDTO.getUserId())) {
            result.setMsg("参数错误，userId 为空");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        if (visitorRequestDTO == null || StringUtils.isEmpty(visitorRequestDTO.getVisitorPhoneNum())) {
            result.setMsg("手机号码为空，此次修改添加失败!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        if (visitorRequestDTO == null || StringUtils.isEmpty(visitorRequestDTO.getVisitorRealName())) {
            result.setMsg("姓名为空，此次修改失败!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return  result;
        }



        Visitor dbVisitor = visitorRepository.findByUserId(visitorRequestDTO.getUserId());
        if(dbVisitor == null){
            result.setMsg("参数错误，用户不存在");
            result.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
            return result;
        }

        Visitor oldVisitor = visitorRepository.findByUserId(visitorRequestDTO.getUserId());


        oldVisitor.setRoleId(visitorRequestDTO.getRoleId());


        Visitor newVisitor =  visitorRepository.saveAndFlush(oldVisitor);
        VisitorResponseDTO dto = VisitorUtils.copyToDTO(newVisitor);
        result.setResultCode(ResultCode.SUCC.getCode());
        result.setMsg("更新成功");
        result.setResult(dto);
        return result;
    }

    @ApiOperation(value = "初始化操作用户的密码", notes = "初始化操作用户的密码", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", value = "操作用户ID", required = true, dataType = "String")
    })
    @RequestMapping(value =Routes.CRM_VISITOR_INIT_PWD, method = RequestMethod.PUT)
    public ResponseBase<VisitorResponseDTO> updateVisitorNameVisitorDescription(@PathVariable(value = "userId") String userId) {
        ResponseBase<VisitorResponseDTO> result = new ResponseBase<>();

        if (  StringUtils.isEmpty(userId)) {
            result.setMsg("参数错误，userId 为空");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        Visitor dbVisitor = visitorRepository.findByUserId(userId);
        if(dbVisitor == null){
            result.setMsg("参数错误，用户不存在");
            result.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
            return result;
        }
        dbVisitor.setPassword("666666");
        visitorRepository.saveAndFlush(dbVisitor);
        result.setResultCode(ResultCode.SUCC.getCode());
        result.setMsg("更新成功");
        return result;
    }



}
